﻿using System;
using Core.DataAccess.Tools.Interfaces;
using NHibernate;

namespace Core.DataAccess.Tools.Implementations
{
    public class Repository<T> : IRepository<T>, IDisposable
    {
        private readonly IConversation conversation;

        public Repository(IConversation conversation)
        {
            this.conversation = conversation;
            conversation.Start();
            conversation.Pause();
        }

        public ICriteria  GetAll()
        {
            conversation.Resume();
            var criteria = conversation.Session.CreateCriteria(typeof (T));
            conversation.Pause();
            return criteria;
        }

        public T  Get<U>(U id)
        {
            conversation.Resume();
            var obj = conversation.Session.Get<T>(id);
            conversation.Pause();
            return obj;
        }

        public void  Save(T entity)
        {
            conversation.Resume();
            conversation.Session.Save(entity);
            conversation.Pause();
        }

        public void  Update(T entity)
        {
            conversation.Resume();
            conversation.Session.SaveOrUpdate(entity);
            conversation.Pause();
        }

        public void  Delete<U>(U id)
        {
            conversation.Resume();
            conversation.Session.Delete(conversation.Session.Get<T>(id));
            conversation.Pause();
        }

        public void Dispose()
        {
            conversation.End();
        }

        ~Repository()
        {
            this.Dispose();
        }

    }
}
